
#include "app.h"
/*start adv*/

static void sensor_read(void* arg);

const char *name = "CANNON_TEST";
uint8_t tx_power_level = 7;
uint16_t adv_interval = 100;

void jsensor_app_set_sensors(void)
{
  
	jsensor_app_set_sensor(JSENSOR_TYPE_HUMITY_TEMP);
	jsensor_app_set_sensor(JSENSOR_TYPE_PRESSURE);
	jsensor_app_set_sensor(JSENSOR_TYPE_MOTION_6AXIS);
	jsensor_app_set_sensor(JSENSOR_TYPE_MAGNET);
}
	
void on_ready(void)
{
  uint8_t bdAddr[6];
 
  HCI_get_bdAddr(bdAddr);
	/*Config Adv Parameter And Ready to Adv*/
	ble_set_adv_param((char *)name, bdAddr, tx_power_level, adv_interval);
	ble_device_start_advertising();
 
}

static void sensor_read(void* arg)
{
 static uint8_t test_flag = 1;
 
	// sensor read temperature & humidity
	{
		uint16_t humidity;
  uint16_t temperature;
		JSensor_HUM_TEMP_Typedef tdef;
	
		tdef.humidity = &humidity;
		tdef.temperature = &temperature;
	
		if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_HUMITY_TEMP, (void *)&tdef)) {
			if((humidity == 0x00) || (humidity == 0xFF))
				return;
		
    }
	}
	// sensor read pressure
	{
		JSensor_Press_Typedef tdef;
		uint32_t pressure;
    
		tdef.pressure = &pressure;
		
		if (JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_PRESSURE, (void *)&tdef)) {
			if((pressure == 0x00) || (pressure == 0xFF))
				return;
				
    }
	}
	// sensor read magenetometer 
	{
		JSensor_MAG_Typedef tdef;
		uint8_t  MAG[6],i;
		tdef.MAG = MAG;

		if(JSENSOR_OK == jsensor_app_read_sensor(JSENSOR_TYPE_MAGNET, (void *)&tdef)) {
				for(i = 0; i < 6;i++){
      if((MAG[i] != 0x00)&&(MAG[i] != 0xFF)){
       test_flag = 1;
       break;
      }else{
       test_flag = 0;
      }
     
    }
    
    if(test_flag == 0){
       return;
    }
    
		}
  
	}
	// sensor read motion 6 AXIS
	{
    if(sensor_acc_selftest() != 0){
      return;
    }
  
 }
 
 {
    if(sensor_gyro_selftest() != 0){
      return;
    } 
 
 }
  //sensor test pass
  BSP_LED_On(LED0);

}



/* Device On Message */
void ble_device_on_message(uint8_t type, uint16_t length, uint8_t* value)
{
	
	if(type == 0x00){
		if(*value == 0x55){
			run_after_delay(sensor_read, NULL, 1000);
		}
		
	}
			
}
/* Device on connect */
void ble_device_on_connect(void)
{
	
 BLE_WAIT_REMOTE_ENABLE_NOTIFY;
	
}
/* Device on disconnect */
void ble_device_on_disconnect(uint8_t reason)
{
	/* Make the device connectable again. */
	Ble_conn_state = BLE_CONNECTABLE;
	ble_device_start_advertising();
}
